/*
 * @(#)ImprovedNamingStrategy.java
 * 2016年8月25日 上午9:30:19
 * 
 * Copyright (c) 2016 QiYunInfoTech - All Rights Reserved.
 * ====================================================================
 * The QiYunInfoTech License, Version 1.0
 *
 * This software is the confidential and proprietary information of QiYunInfoTech.
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into with QiYunInfoTech.
 */
package com.qyxx.platform.common.jpa;

import org.apache.commons.lang.StringUtils;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;

/**
 * 解决Hibernate从4到5时NamingStrategy问题
 * 
 * @author bobgao
 * @version 1.0 2016年8月25日 上午9:30:19
 * @since jdk1.7
 */

public class ImprovedNamingStrategy
		implements PhysicalNamingStrategy {

	@Override
	public Identifier toPhysicalCatalogName(Identifier identifier,
			JdbcEnvironment jdbcEnv) {
		return convert(identifier);
	}

	@Override
	public Identifier toPhysicalColumnName(Identifier identifier,
			JdbcEnvironment jdbcEnv) {
		return convert(identifier);
	}

	@Override
	public Identifier toPhysicalSchemaName(Identifier identifier,
			JdbcEnvironment jdbcEnv) {
		return convert(identifier);
	}

	@Override
	public Identifier toPhysicalSequenceName(Identifier identifier,
			JdbcEnvironment jdbcEnv) {
		return convert(identifier);
	}

	@Override
	public Identifier toPhysicalTableName(Identifier identifier,
			JdbcEnvironment jdbcEnv) {
		return convert(identifier);
	}

	private Identifier convert(Identifier identifier) {
		if (identifier == null
				|| StringUtils.isBlank(identifier.getText())) {
			return identifier;
		}

		String regex = "([a-z])([A-Z])";
		String replacement = "$1_$2";
		String newName = identifier.getText()
				.replaceAll(regex, replacement).toLowerCase();
		return Identifier.toIdentifier(newName);
	}

	public static void main(String[] args) {
		String regex = "([a-z])([A-Z])";
		String replacement = "$1_$2";
		String newName = "createTime".replaceAll(regex, replacement)
				.toLowerCase();
		System.out.println(newName);
	}
}
